package br.ufrj.neg.reuniao.servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.velocity.tools.view.VelocityViewServlet;

import br.ufrj.neg.bean.Idioma;
import br.ufrj.neg.constants.General;
import br.ufrj.neg.reuniao.bean.ArtefatoBean;
import br.ufrj.neg.reuniao.bean.EncaminhamentoBean;
import br.ufrj.neg.reuniao.bean.ReuniaoBean;
import br.ufrj.neg.reuniao.bean.TipoArtefatoBean;
import br.ufrj.neg.reuniao.model.TipoArtefatoModel;
import br.ufrj.neg.util.Data;

public class CadastrarArtefatoReuniaoAction extends VelocityViewServlet{

	private static final long serialVersionUID = -1502095409248120929L;
	//private static Logger log = Logger.getLogger("rootLogger");

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		
		//ArtefatoModel am = new ArtefatoModel();
		
		try {
			/*
			 * Pega a sessao
			 */
			HttpSession session = request.getSession(false);
						
			/*
			 * Pega os parametros passados
			 */
			
			InputStream arquivo = null;
			String descricao = new String();
			String nome = new String();
			String caminho = new String();
			Integer reuniao = 0;
			Integer tipoArtefato = 0;
			String descReuniao = new String();
			String local = new String();
			String data = new String();
			String hora = new String();
			Integer tipoReuniao = 0;
			String encaminhamentoReuniao = new String();			
			Integer idEncaminhamento = 0;

			Idioma idioma = (Idioma) request.getAttribute("idioma");
			ArtefatoBean ab = new ArtefatoBean(idioma);
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			
			if (isMultipart)
			{
				// Create a new file upload handler
				ServletFileUpload upload = new ServletFileUpload();
	
				// Parse the request
				FileItemIterator iter = upload.getItemIterator(request);
				
				FileItemStream  fitem = null;
				InputStream stream = null;
				while (iter.hasNext())  
				{  
					fitem = (FileItemStream) (iter.next());
				    stream = fitem.openStream();
	
					if (fitem.isFormField())  
					{  
						if(fitem.getFieldName().equals("descricaoArtefato"))  
						{  
							descricao = General.toUTF8( Streams.asString(stream) );  
						}
						else if(fitem.getFieldName().equals("caminhoArtefato"))  
						{  
							caminho = General.toUTF8( Streams.asString(stream) );   
						}
						else if(fitem.getFieldName().equals("tipoArtefato"))  
						{  
							tipoArtefato = Integer.parseInt(Streams.asString(stream));  
						}
						else if(fitem.getFieldName().equals("descricao"))  
						{  
							descReuniao = General.toUTF8(Streams.asString(stream));  
						}
						else if(fitem.getFieldName().equals("local"))  
						{  
							local = General.toUTF8(Streams.asString(stream));  
						}
						else if(fitem.getFieldName().equals("data"))  
						{  
							data = General.toUTF8(Streams.asString(stream));  
						}
						else if(fitem.getFieldName().equals("hora"))  
						{  
							hora = General.toUTF8(Streams.asString(stream));  
						}
						else if(fitem.getFieldName().equals("tipoReuniao"))  
						{  
							tipoReuniao = Integer.parseInt(Streams.asString(stream));  
						}
						else if(fitem.getFieldName().equals("encaminhamento"))  
						{  
							encaminhamentoReuniao = General.toUTF8(Streams.asString(stream));  
						}
						else if(fitem.getFieldName().equals("tipoReuniao"))  
						{  
							tipoReuniao = Integer.parseInt(Streams.asString(stream));  
						}
						else if(fitem.getFieldName().equals("idReuniao"))  
						{  
							reuniao = Integer.parseInt(Streams.asString(stream));  
						}
						
					}  
					else  
					{  
						arquivo = fitem.openStream();
						nome = General.toUTF8( fitem.getName() );
						break;
					}  
				}  

			}
			
			/*
			 * Monta o NegociacaoBean
			 */
			 
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int len_buffer = 3000;
			byte buf[] = new byte[len_buffer];
			int lidos = 1;
			
			lidos = arquivo.read(buf,0,3000);
			while( lidos > -1 ){							
				baos.write(buf,0,lidos);	
				lidos = arquivo.read(buf,0,3000);
			}
			
			
			TipoArtefatoModel tam = new TipoArtefatoModel();
			ab.setDescricao(descricao);
			ab.setNome(nome);	
			ab.setReuniao(reuniao);
			ab.setTipoArtefato(tipoArtefato);
			
			TipoArtefatoBean tab = new TipoArtefatoBean(idioma);
			tab.setId(tipoArtefato);			
			String tipoArtefatoDescricao = tam.getTipoArtefato(tab).getDescricao();
			ab.setTipoArtefatoDescricao(tipoArtefatoDescricao);			
			ab.setArquivoAsByte(baos.toByteArray());
			ab.setData(new Data());
			ab.setDataFormatada(idioma.getData(ab.getData()));
			
			ReuniaoBean rb;

			synchronized(session){
				rb = (ReuniaoBean) session.getAttribute("ReuniaoBean");
			}
						
			ab.setIndice(rb.getArtefatos().size());
			rb.setDescricao(descReuniao);
			rb.setLocal(local);
			if ((data != null && data.length() > 0)){
				if(hora == null || hora.length() == 0)
					rb.setData(new Data(data));
				else
					rb.setData(new Data(data, hora));
			}
			else{
				rb.setData(null);
			}
			rb.setHora(hora);
			rb.setTipoReuniao(tipoReuniao);
			EncaminhamentoBean eb = new EncaminhamentoBean();
			eb.setId(idEncaminhamento);
			eb.setDescricao(encaminhamentoReuniao);
			rb.setEncaminhamento(eb);
			rb.getArtefatos().add(ab);
			
			synchronized(session){
				session.setAttribute("ReuniaoBean", rb);
			}
			request.setAttribute("idReuniao", new Integer(reuniao));
			
			request.getRequestDispatcher("reuniao.editar").forward(request, response);
				
		} catch (Exception e) {
			System.out.println(e);
			request.getRequestDispatcher(General.TELA_ERRO_500).forward(request,
					response);
		}
	}
	
	
	
}
